import { v4 as uuidv4 } from 'uuid';
import parametersJson from './parameters.json';

// 参数类型定义
export interface Parameter {
    id: string;
    name: string;
    defaultValue: string;
    type: string;
    description: string;
}

// 模拟数据存储
let parameters: Parameter[] = parametersJson.parameters;

// 保存数据到本地存储
const saveToLocalStorage = () => {
    localStorage.setItem('parameters', JSON.stringify(parameters));
};

// 从本地存储加载数据
const loadFromLocalStorage = () => {
    const storedData = localStorage.getItem('parameters');
    if (storedData) {
        parameters = JSON.parse(storedData);
    }
};

// 初始化数据
loadFromLocalStorage();

// 获取所有参数
export const getParameters = (): Parameter[] => {
    return [...parameters];
};

// 根据ID获取参数
export const getParameterById = (id: string): Parameter | undefined => {
    return parameters.find(param => param.id === id);
};

// 创建新参数
export const createParameter = (parameter: Omit<Parameter, 'id'>): Parameter => {
    const newParam = {
        id: uuidv4(),
        ...parameter
    };
    parameters.push(newParam);
    saveToLocalStorage();
    return newParam;
};

// 更新参数
export const updateParameter = (id: string, updates: Partial<Parameter>): Parameter | null => {
    const index = parameters.findIndex(param => param.id === id);
    if (index === -1) {
        return null;
    }

    parameters[index] = {
        ...parameters[index],
        ...updates
    };

    saveToLocalStorage();
    return parameters[index];
};

// 删除参数
export const deleteParameter = (id: string): boolean => {
    const initialLength = parameters.length;
    parameters = parameters.filter(param => param.id !== id);
    saveToLocalStorage();
    return parameters.length < initialLength;
};